package com.flu.holidays.service.impl.json;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.flu.holidays.constant.DayEnum;
import com.flu.holidays.modeel.DayTypeModel;
import com.flu.holidays.service.HolidayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class HolidayServiceJsonImpl implements HolidayService {


    private final JSONObject holidayJson;


    @Override
    public DayTypeModel getDayType() {
        return getDayType(DateUtil.today());
    }

    @Override
    public DayTypeModel getDayType(String date) {

        DateTime dateTime = DateUtil.parse(date, DatePattern.NORM_DATE_FORMATTER);
        String yearStr = dateTime.year()+"";
        //没有对应年份的假日配置
        if (!holidayJson.containsKey(yearStr)){
            return getDefaultModel(dateTime);
        }
        JSONObject yearJson = holidayJson.getJSONObject(yearStr);
        //指定日期不是节假日/调休
        if (!yearJson.containsKey(date)){
            if (DateUtil.isWeekend(dateTime)){
                return DayEnum.WEEKEND.toModel();
            }
            return DayEnum.WORKING_DAY.toModel();

        }
        //指定日期是节假日/调休
        JSONObject dayJson = yearJson.getJSONObject(date);
        DayTypeModel result = new DayTypeModel();
        Integer code = dayJson.getInt("type");
        result.setCode(code);
        DayEnum.getByCodeInt(code).ifPresent(
                dayEnum -> result.setDesc(dayEnum.getDesc())
        );
        result.setType(dayJson.getStr("holidayType"));
        return result;
    }


    public JSONObject getJsonConfig(){
        return holidayJson;
    }
}
